package catalog;

import java.util.HashMap;
import java.util.Map;

import stalker.Stalker;

/**
 * Stores bindings from names to keys
 */

public class UniqueNamedStalkerCatalog {
  
private static final boolean CHECK_REP_ON = true;
  
  private final Map<String, Long> name_id_bindings;
  
  private void checkRep() {
    assert (name_id_bindings != null) :
      "StalkerUniqueNamedCatalog: field may not be null";
    if (!CHECK_REP_ON) {
      return;
    }
    for (Long l : name_id_bindings.values()) {
      assert (Stalker.getStalker(l) != null) :
        "StalkerUniqueNamedCatalog: Inconsistent data";
    }
  }
  
  /**
   * Constructs a new stalker unique named catalog
   */
  public UniqueNamedStalkerCatalog() {
    name_id_bindings = new HashMap<String, Long>();
  }
  
  /**
   * Adds a UniqueNamedStalker and updates all corresponding fields
   * @requires stalker is not null, new_user is new
   * @param stalker  the new user to be added
   * @complexity A(1)
   */
  public synchronized void add(Stalker stalker) {
    assert stalker != null;
    assert (!(name_id_bindings.containsKey(stalker.getName()))) :
      "UniqueNamedStalkerCatalog: Username already present";
    
    name_id_bindings.put(stalker.getName(), stalker.getID());
    checkRep();
  }
  
  /**
   * Checks whether a name is already taken.
   * @requires name is not null
   * @param username  the name that's going to be checked
   * @return true iff name is already present
   * @complexity A(1)
   */
  public synchronized boolean contains(String name) {
    assert name != null;
    return name_id_bindings.containsKey(name);
  }
  
  /**
   * Retrieves an ID given its name
   * @requires name is not null, name is present
   * @param username name of the Stalker that's being searched in this context
   * @return the ID of the stalker whose name is given in this context
   */
  public synchronized long getIDFromName(String name) {
    assert (name != null);
    assert (this.contains(name));
    return name_id_bindings.get(name);
  }
    
}
